using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Messaging;
using System.Text;
using Universe.Remoting.Sinks;

namespace Universe.Remoting.Extensions
{
    class TrafficServerSink: BaseCustomSink
    {
        private long requestLength = 0;
        
        protected override void ProcessRequest(IMessage message, ITransportHeaders headers, ref Stream stream, ref object state)
        {
            TrafficStatisticConfiguration.Server.UpdateTotal(1, 0, 0);

            if (stream != null)
            {
                MemoryStream copy = new MemoryStream();
                byte[] buffer = new byte[1024];
                while (true)
                {
                    int n = stream.Read(buffer, 0, buffer.Length);
                    if (n <= 0)
                        break;

                    copy.Write(buffer, 0, n);
                }

                requestLength = copy.Length;
                stream = copy;
                stream.Position = 0;

                TrafficStatisticConfiguration.Server.UpdateTotal(0, 0, requestLength);
            }
        }

        protected override void ProcessResponse(IMessage message, ITransportHeaders headers, ref Stream stream, object state)
        {
            long sent = 0;

            if (stream != null)
            {
                if (stream.CanSeek)
                {
                    sent = stream.Length;
                    TrafficStatisticConfiguration.Server.UpdateTotal(0, sent, 0);
                }
            }

            string typeName, methodName;
            if (Info.GetMessageInfo(message, out typeName, out methodName))
            {
                TrafficStatisticConfiguration.Server.Update(typeName, methodName, sent, requestLength);
            }

       }


    }
}